import Taro from "@tarojs/taro";
import { objectToQueryString } from "./utils";

const API_PRE = 'http://localhost:3000';

const tools = {
  /**
   * 请求后端数据方法
   * @param {*} param0
   * @returns
   */
  request: ({ url = "", params = {}, method = "GET", ...rest }) => {
    return new Promise((resolve, reject) => {
      Taro.request({
        url: `${API_PRE}${url}`,
        data: params,
        method,
        ...rest,
      })
        .then((res) => {
          const { data } = res;
          if (data?.code === 1) {
            resolve(data);
          } else {
            reject(res);
          }
        })
        .catch((err) => {
          reject(err);
        });
    });
  },
  /**
   * 页面loading
   */
  showLoading: (param = "") => {
    let defaultOptions = {
      title: '加载中...',
      mask: true,
    }
    if (typeof param === 'string') {
      defaultOptions.title = param
    } else if (typeof param === 'object' && param !== null) {
      Object.assign(defaultOptions, param);
    }
    return Taro.showLoading(defaultOptions);
  },
  hideLoading: () => {
    Taro.hideLoading();
  },
  /**
   * 页面提示
   */
  showToast: (params) => {
    let options = {
      title: '温馨提示',
      icon: 'none',
      mask: true,
      duration: 2000,
    }
    if (typeof params === 'string') {
      options.title = params;
    } else if (typeof params === 'object' && params !== null) {
      Object.assign(options, params);
    } else {
      throw new Error('参数类型错误，需要字符串或者对象');
    }
    return Taro.showToast(options);
  },
  /**
   * 路由跳转
   * url 页面路径
   * parmas 页面参数
   */
  navigateTo: ({ url, params }) => {
    const queryStr = objectToQueryString(params);
    return Taro.navigateTo({ url: `${url}?${queryStr}` });
  }
};

export default tools;
